/*
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.layoutlib.reflection

import com.intellij.util.ReflectionUtil
import java.util.Collections
import java.util.WeakHashMap

/**
 * This class is intended to be used by the bytecode manipulation transform in ModuleClassLoader to replace standard ThreadLocal class in
 * the user and third party libs code. It allows to track initialization of all the ThreadLocal objects so that they can be released when
 * they no longer needed and therefore prevent them from retaining the corresponding ModuleClassLoader.
 */
open class TrackingThreadLocal<T> : ThreadLocal<T>() {
  init {
    // 1: com.intellij.util.ReflectionUtil
    // 2: com.android.layoutlib.reflection.TrackingThreadLocal
    // 3: the actual caller of this constructor
    track(ReflectionUtil.getCallerClass(3).classLoader, this)
  }

  companion object {
    private val threadLocalsMap: WeakHashMap<ClassLoader, MutableSet<ThreadLocal<*>>> = WeakHashMap()

    @Synchronized
    fun track(classLoader: ClassLoader, threadLocal: ThreadLocal<*>) {
      threadLocalsMap.computeIfAbsent(classLoader) { Collections.newSetFromMap(WeakHashMap()) }.add(threadLocal)
    }

    @JvmStatic
    @Synchronized
    fun clearThreadLocals(classLoader: ClassLoader) = threadLocalsMap.remove(classLoader)
  }
}
